﻿namespace RuoVea.OmiApi.UserRole.Service;

/// <summary>
/// 系统角色服务🔷
/// </summary>
[ApiExplorerSettings(GroupName = "system")]
public class SysRoleService : IApplicationService
{
    private readonly ICurrentUser _currentUser;
    private readonly SugarRepository<SysRole> _sysRoleRep;
    private readonly SysUserRoleService _sysUserRoleService;
    private readonly SysCacheService _sysCacheService;
    /// <summary>
    /// 
    /// </summary>
    /// <param name="currentUser"></param>
    /// <param name="sysRoleRep"></param>
    /// <param name="sysUserRoleService"></param>
    /// <param name="sysCacheService"></param>
    public SysRoleService(ICurrentUser currentUser,
        SugarRepository<SysRole> sysRoleRep,
        SysUserRoleService sysUserRoleService, SysCacheService sysCacheService)
    {
        _currentUser = currentUser;
        _sysRoleRep = sysRoleRep;
        _sysUserRoleService = sysUserRoleService;
        _sysCacheService = sysCacheService;
    }

    /// <summary>
    /// 获取角色分页列表 🔹
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("获取角色分页列表")]
    public async Task<PageResult<SysRole>> Page(PageRoleInput input)
    {
        return await _sysRoleRep.AsQueryable()
            .WhereIF(!_currentUser.IsSuperAdmin && !_currentUser.IsTenantAdmin, u => u.Creator == _currentUser.UserId) // 若非超管且非系统管理员，则只能操作自己创建的角色
            .WhereIF(!string.IsNullOrWhiteSpace(input.Name), u => u.Name.Contains(input.Name))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Code), u => u.Code.Contains(input.Code))
            .OrderBy(u => new { u.Sort, u.Id })
            .ToPageAsync(input.PageNo, input.PageSize);
    }

    /// <summary>
    /// 获取角色列表 🔹
    /// </summary>
    /// <returns></returns>
    [DisplayName("获取角色列表")]
    public async Task<List<RoleOutput>> GetList()
    {
        // 当前用户已拥有的角色集合
        var roleIdList = _currentUser.IsSuperAdmin ? new List<long>() : await _sysUserRoleService.GetUserRoleIdList(_currentUser.UserId);

        return await _sysRoleRep.AsQueryable()
            .WhereIF(!_currentUser.IsSuperAdmin && !_currentUser.IsTenantAdmin, u => u.Creator == _currentUser.UserId || roleIdList.Contains(u.Id)) // 若非超管且非系统管理员，则只显示自己创建和已拥有的角色
            .Where(u => u.IsDisable == YesOrNot.N) // 非禁用的
            .OrderBy(u => new { u.Sort, u.Id }).Select<RoleOutput>().ToListAsync();
    }

    /// <summary>
    /// 增加角色 🔹
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost("Add")]
    [DisplayName("增加角色")]
    public async Task AddRole(AddRoleInput input)
    {
        if (await _sysRoleRep.IsAnyAsync(u => u.Name == input.Name && u.Code == input.Code))
            throw new AggregateException(i18n.data_exists);

        var newRole = await _sysRoleRep.AsInsertable(input.Adapt<SysRole>()).ExecuteReturnEntityAsync();
        input.Id = newRole.Id;
    }

    /// <summary>
    /// 更新角色 🔹
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPut("Update"),]
    [DisplayName("更新角色")]
    public async Task UpdateRole(AddRoleInput input)
    {
        if (await _sysRoleRep.IsAnyAsync(u => u.Name == input.Name && u.Code == input.Code && u.Id != input.Id))
            throw new AggregateException(i18n.data_exists);

        await _sysRoleRep.AsUpdateable(input.Adapt<SysRole>()).IgnoreColumns(true).ExecuteCommandAsync();

    }

    /// <summary>
    /// 删除角色 🔹
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [UnitOfWork]
    [HttpDelete("Delete"),]
    [DisplayName("删除角色")]
    public async Task DeleteRole(DeleteRoleInput input)
    {
        // 禁止删除系统管理员角色
        var sysRole = await _sysRoleRep.GetFirstAsync(u => u.Id == input.Id) ?? throw new AggregateException(i18n.record_not_exists);
        if (sysRole.Code == CommonConst.SysAdminRole)
            throw new AggregateException(i18n.prohibit_delete_admin);

        // 若角色有用户则禁止删除
        var userIds = await _sysUserRoleService.GetUserIdList(input.Id);
        if (userIds != null && userIds.Count > 0)
            throw new AggregateException(i18n.role_has_accounts);

        await _sysRoleRep.DeleteAsync(sysRole);

        // 级联删除用户角色数据
        await _sysUserRoleService.DeleteUserRoleByRoleId(sysRole.Id);

    }

    /// <summary>
    /// 设置角色状态 🔹
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("设置角色状态")]
    public async Task<int> SetStatus(RoleInput input)
    {
        if (!input.IsDisable.IsDefined<YesOrNot>())
            throw new AggregateException(i18n.dict_status_error);

        return await _sysRoleRep.AsUpdateable()
            .SetColumns(u => u.IsDisable == input.IsDisable)
            .Where(u => u.Id == input.Id)
            .ExecuteCommandAsync();
    }
}